﻿using System;
using System.Windows;
using System.Windows.Controls;
using dotNetMagazin201108.PresentationLayer.Views;
using dotNetMagazin201108.BusinessLayer;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace dotNetMagazin201108.PresentationLayer.Presenter
{
    public class ContactBrowserPresenter
    {
        private ContactBrowserView View;
        private ContactFormPresenter FormPresenter;
        private bool ViewEventsEnabled = true;
        
        public ContactBrowserPresenter(ContactBrowserView view) 
        {
            View = view;

            if (View.List.Items.Count == 0)
            {
                View.List.Items.Add("items loading...");
                View.List.SelectedIndex = -1;
                View.List.SelectionChanged += List_SelectionChanged;
            }
            ContactFormView contactFormView = View.contactFormView1;
            FormPresenter = new ContactFormPresenter(contactFormView);
            FormPresenter.ContactAdded += FormPresenter_ContactAdded;
            FormPresenter.ContactModified += FormPresenter_ContactModified;
            
            Thread t = new Thread(delegate()
            {
                ContactRepository contacts = Factory.CreateContactRepository();
                IEnumerable<Contact> list = contacts.GetAll().ToArray();
                
                View.Dispatcher.BeginInvoke(delegate()
                {
                    View.List.Items.Clear();
                    if (list != null)
                    {
                        View.List.Items.Add(new ContactListDto() { Text = "Neuen Kontakt anlegen", Id = 0 });
                        foreach (var contact in list)
                        {
                            View.List.Items.Add(CreateDtoTextFromContact(contact));
                        }
                    }
                    else
                    {
                        View.List.Items.Add("Kontakte konnten nicht geladen werden.");
                    }
                    View.List.SelectedIndex = 0;
                });
            });
            t.Start();
        }
        
        private void FormPresenter_ContactModified(object sender, EventArgs e)
        {
            ViewEventsEnabled = false;
            View.Dispatcher.BeginInvoke(delegate()
            {
                Contact contact = FormPresenter.GetContactFromUI();
                for (int i = 0; i < View.List.Items.Count; i++)
                {
                    if (((ContactListDto)View.List.Items[i]).Id == contact.Id)
                    {
                        View.List.Items[i] = CreateDtoTextFromContact(contact);
                        View.List.SelectedIndex = i;
                        break;
                    }
                }
                ViewEventsEnabled = true;
            });
        }
        private void FormPresenter_ContactAdded(object sender, EventArgs e)
        {
            ViewEventsEnabled = false;
            View.Dispatcher.BeginInvoke(delegate()
            {
                Contact contact = FormPresenter.GetContactFromUI();
                View.List.Items.Add(CreateDtoTextFromContact(contact));
                View.List.SelectedIndex = View.List.Items.Count - 1;
                ViewEventsEnabled = true;
            });
        }
        private void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!ViewEventsEnabled) return;
            ViewEventsEnabled = false;
            bool loadContact = true;
            if (FormPresenter.ViewDirtyFlag)
            {
                var result = MessageBox.Show("Möchten Sie die Änderungen wirklich verwerfen?", "Kontaktliste", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    loadContact = false;
                    if (e.RemovedItems.Count == 1)
                    {
                        View.List.SelectedItem = e.RemovedItems[0];
                    }
                    else
                    {
                        View.List.SelectedIndex = 0;
                    }
                }
            }
            if (loadContact)
            {
                ContactListDto dto = (ContactListDto)View.List.SelectedItem;

                Thread t = new Thread(delegate()
                {
                    CompanyRepository companyRepository = Factory.CreateCompanyRepository();
                    IEnumerable<CompanyListDto> companies = companyRepository
                        .GetAll().Select(c => new CompanyListDto() { Text = c.Name, Id = c.Id }).ToArray();

                    if (dto.Id == 0)
                    {
                        View.Dispatcher.BeginInvoke(() => FormPresenter.FillUI(new Contact(), companies));
                    }
                    else
                    {
                        ContactRepository contacts = Factory.CreateContactRepository();
                        Contact contact = contacts.GetById(dto.Id);
                        View.Dispatcher.BeginInvoke(() => FormPresenter.FillUI(contact, companies));
                    }
                });
                t.Start();
            }
            ViewEventsEnabled = true;
        }

        private ContactListDto CreateDtoTextFromContact(Contact c)
        {
            return new ContactListDto() { Text = c.LastName, Id = c.Id };
        }
    }
}
